package com.huawei.cloud.phone.management.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

@Slf4j
public final class JsonUtils {
    private JsonUtils() {
    }

    public static <T> T parseData(String data, Class<T> clazz) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readValue(data, clazz);
        } catch (JsonProcessingException e) {
            log.error("parse data failed", e);
            throw new RuntimeException(e.getOriginalMessage());
        }
    }

    public static <T> List<T> parseData(String data, TypeReference<List<T>> reference) {
        ObjectMapper mapper = new ObjectMapper();

        try {
            return mapper.readValue(data, reference);
        } catch (JsonProcessingException e) {
            log.error("parse data failed", e);
            throw new RuntimeException(e.getOriginalMessage());
        }
    }

    public static String toJsonString(Object data) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(data);
        } catch (JsonProcessingException e) {
            log.error("parse data failed", e);
            throw new RuntimeException(e.getMessage());
        }
    }
}
